ShoppingCart = {}

ShoppingCart.clear = function(id) {
    $.post("controllers/carts.php",{'clear':1},function(data) {
        if (callback) {
            callback(data);
        }
    });
}

ShoppingCart.buy = function(id,callback) {
    $.post("controllers/carts.php",{'book_id':id,'add':1},function(data) {
        if (callback) {
            callback(data);
        }
    });
}

ShoppingCart.get = function(callback) {
    $.getJSON("controllers/carts.php",function(data) {
        callback(data.collection);
    });
}

ShoppingCart.setQty = function(id,qty) {
    $.post("controllers/carts.php",{'book_id':id,'quantity':qty},function(data) {
        if (callback) {
            callback(data);
        }
    });
}

ShoppingCart.remove = function(id,callback) {
    $.post("controllers/carts.php",{book_id:id, remove:1},function(data) {
        if (callback) {
            callback(data);
        }
    });
}

/*
 * user interface
 */

function renderCart(renderTo,backCallback) {
    var prevLocation = window.location.hash;
    window.location.hash = '#cart=1';
    var clear = $("<a></a>",{href:'',text:'clear cart'})
        .click(function() {
            ShoppingCart.clear();
            window.location.hash = prevLocation;
            renderCart(renderTo,backCallback);
            return false;
        });
    var back = null;
    if (backCallback) {
        back = $("<a></a>",{href:'',text:'back'})
            .click(function() {
                backCallback(prevLocation);
                return false;
            });
    }

    var cartContent = $(
    '<table class="cartContent">'+
    '<tr><th class="cartT">book</th><th>price (per unit)</th><th>quantity</th>'+
    '<th>remove</th></tr>'+
    '</table>'
    );

    var order = $('<a></a>',{href:'',text:'order'})
        .click( function() {
            renderOrderForm(renderTo);
            return false;
        });
    order.hide();

    ShoppingCart.get(function(data) {
        $.each(data,function(i,item) {
            var newItem = $(
            '<tr><td class="cartT">'+item.book.title+'</td>'+
            '<td>'+item.book.price+'</td>'+
            '<td class="cartQty">'+item.quantity+' <a href="">(change)</a></td>'+
            '<td><a class="cartRem" href="">remove</a></td></tr>'
            );
            newItem.find('.cartRem').click(function() {
                ShoppingCart.remove(item.book.id,function(data) {
                    if (data && data.error) {
                        alert(data.error);
                    } else {
                        window.location.hash = prevLocation;
                        renderCart(renderTo,backCallback);
                    }
                });
                return false;
            });

            var showQtyForm = function() {
                var origQtyContent = newItem.find('.cartQty').clone(true);
                newItem.find('.cartQty').html(
                 '<form action="controllers/carts.php" method="post">'+
                 '<input type="hidden" name="book_id" value="'+item.book.id+'">'+
                 '<input type="text" size="5" name="quantity" value='+item.quantity+'>'+
                 '<input type="image" name="qtyconfirm" src="Add.png" alt="change">'+
                 '</form>'
                 );
                newItem.find('.cartQty').find('form').ajaxForm({
                    dataType:'json',
                    success: function(data) {
                        if (data && data.error) {
                            alert(data.error);
                        } else {
                            window.location.hash = prevLocation;
                            renderCart(renderTo,backCallback);
                        }
                    }
                });
                var closelink = $('<a></a>',{href:''});
                closelink.append('<img style="border: 0" src="Delete.png" alt="x"/>');
                closelink.click(function() {
                    newItem.find('.cartQty').replaceWith( origQtyContent );
                    return false;
                });
                newItem.find('.cartQty > form').append(closelink);
            }
            newItem.find('.cartQty > a').click(function() {
                showQtyForm();
                return false;
            });
            cartContent.append(newItem);
        });
        if (data.length != 0) { order.show(); }
    });

    $(renderTo).html( $('<p></p>').append(clear) );
    $(renderTo).append( cartContent );
    $(renderTo).append( order );
    if (backCallback) {
        $(renderTo).append( $('<p></p>').append(back) );
    }
}

function renderOrderForm(renderTo) {
    window.location.hash = '#order=1';
    var cartContent = $(
    '<table class="cartContent">'+
    '<tr><th class="cartT">book</th><th>price (per unit)</th><th>quantity</th>'+
    '</tr>'+
    '</table>'
    );
    var p_total = $("<p></p>");
    var orderForm = $('<form method="post" action="controllers/orders.php"></form>');

    ShoppingCart.get(function(data) {
        var totalPrice = 0;
        $.each(data,function(i,item) {
            totalPrice += item.book.price*item.quantity;
            var newItem = $(
            '<tr><td class="cartT">'+item.book.title+'</td>'+
            '<td>'+item.book.price+'</td>'+
            '<td class="cartQty">'+item.quantity+'</td></tr>'
            );
            cartContent.append(newItem);
        });
        p_total.html('<p>total price: '+totalPrice+'</p>');
        orderForm.append(
        '<p>If you are happy with the above, please enter your payment details'+
        ' and place an order</p>');
        orderForm.append(
        '<table>'+
        '<tr><td>contact: </td><td><input type="text" name="contact"></td></tr>'+
        '<tr><td>address: </td><td><textarea name="address" cols="15" rows="6"></textarea></td></tr>'+
        '<tr><td>credit card number: </td><td><input type="text" name="creditcard"></td></tr>'+
        '<tr><td>note: </td><td><textarea name="note" cols="15" rows="6"></textarea></tr>'+
        '<tr><td colspan="2"><input type="submit" name="makeorder" value="make an order"></td></tr>'+
        '</table>'
        );
        orderForm.ajaxForm({
            dataType:'json',
            success: function(data) {
                if (data && data.error) {
                    alert(data.error);
                } else {
                    $(renderTo).empty();
                    $(renderTo).append("<p>Disco! Order successfully placed!</p>");
                }
            }
        });
    });    

    $(renderTo).empty();
    $(renderTo).append(cartContent);
    $(renderTo).append(p_total);
    $(renderTo).append(orderForm);
}
